The R rgcapi library
Algorithmic trading has always interested me. The abundance of time-series data, the clear feedback loop, the challenge of building and testing strategies — it’s a domain where you can iterate quickly and see the results immediately. Forex markets were an accessible entry point.
When I decided to build an interface to the Gain Capital API (the backend behind Forex.com), I chose R over Python deliberately. Part of the reason was curiosity: I wanted to properly learn R6 classes, the object-oriented paradigm in R that supports encapsulation and stateful objects. A trading client felt like the right project for that — you need a persistent connection, stateful account information, and clean method dispatch. R6 handles all of that well.
The result is rgcapi, an R package that connects directly to the Gain Capital API.
What is rgcapi?
rgcapi provides a full interface to Gain Capital’s API (V1 and V2). With it you can:
- Manage trading accounts and monitor balances.
- Retrieve real-time market data.
- Automate trade execution and management.
- Extract historical data for analysis and backtesting.
As far as I know, it’s the only package in the R ecosystem with connectivity to the Gain Capital API.
Key Features of rgcapi
- Account Management: Initialize sessions and manage user accounts.
- Market Information: Real-time market quotes, instrument details, and pricing data.
- Trading Operations: Execute trades, manage orders, monitor open positions.
- Historical Data: OHLC and tick data for backtesting and time-series analysis.
Installation
Install directly from GitHub:
# Install devtools if needed
install.packages("devtools")
# Install rgcapi from GitHub
devtools::install_github("athammad/rgcapi")Setting Up Your API Credentials
You’ll need credentials from Forex.com: username, password, and an application key. Initialize the client like this:
library(rgcapi)
# Replace with your actual credentials
IDLOG <- "your_username"
PSWD <- "your_password"
APKEY <- "your_appkey"
# Initialize the client for Gain Capital API V2
client <- GCapiClientV2$new(username = IDLOG, password = PSWD, appkey = APKEY)Example Workflows
1. Retrieve Account Information
account_info <- client$get_account_info()
print(account_info)2. Fetch Market Information
# Get market information for EUR/USD
market_info <- client$get_market_info("EUR/USD")
print(market_info)
# Retrieve specific fields
market_id <- client$get_market_info("EUR/USD", get = "MarketId")
market_name <- client$get_market_info("EUR/USD", get = "Name")
print(market_id)
print(market_name)3. Extract Historical Price Data
# Get latest price data
fromA <- as.integer(as.POSIXct(Sys.Date(), tz = "UTC") - months(1))
toB <- as.integer(as.POSIXct(Sys.time(), tz = "UTC"))
prices <- client$get_prices(
market_id = market_id,
num_ticks = 1,
from_ts = fromA,
to_ts = toB,
price_type = "MID"
)
print(prices)For OHLC data:
# Retrieve OHLC data for the last 24 hours
fromA <- as.integer(as.POSIXct(Sys.Date(), tz = "UTC") - days(1))
toB <- as.integer(as.POSIXct(Sys.time(), tz = "UTC"))
ohlc <- client$get_ohlc(
market_id = market_id,
num_ticks = 4000,
interval = "MINUTE",
span = 30,
from_ts = fromA,
to_ts = toB
)
print(ohlc)4. Execute a Trade
# Place a buy trade
trade_resp <- client$trade_order(
quantity = 1020,
offer_price = prices$Price,
direction = "buy",
trading_acc_id = client$trading_account_id,
market_id = market_id,
market_name = market_name,
stop_loss = 1.060000,
take_profit = 1.080000,
tolerance = 0.0005
)
print(trade_resp)5. Monitor and Manage
# List all open positions
open_positions <- client$list_open_positions()
print(open_positions)Closing a position:
# Close a trade order
close_resp <- client$trade_order(
quantity = 1020,
offer_price = prices$Price,
direction = "sell",
trading_acc_id = client$trading_account_id,
market_id = market_id,
market_name = market_name,
close = TRUE,
order_id = open_positions$OrderId[1]
)
print(close_resp)6. Retrieve Trade History
# Get trade history
trade_history <- client$get_trade_history()
print(trade_history)
Building rgcapi was both a practical tool and a learning project. R6 turned out to be well-suited for this kind of stateful API client — the session management, the account state, and the method dispatch all fit naturally into the class structure. The package is on GitHub at athammad/rgcapi. Let me know if you build something with it.